package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.event.RightTopMenuClickEvent;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.http.EFHttpRequest;
import com.pansoft.newasset.event.OptionMarketEvent;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.WalletAvatarAndNameSetupActivity;
import com.pansoft.openplanet.activity.WalletTypeSelectActivity;
import com.pansoft.openplanet.adapter.ChildWalletListAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.AssetListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.pansoft.openplanet.widget.StarAssetWalletPopup;
import com.pansoft.openplanet.widget.WrapContentLinearLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class EOSWalletListFragment extends BaseFragment implements View.OnClickListener {

    public static final String TAG = "EOSWalletListFragment";
    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ChildWalletListAdapter childWalletListAdapter;
    private ArrayList<AssetListBean> assetList = new ArrayList<>();//当前关注的代币列表
    private int mode = EosNetParamUtil.getEosChainId();
    private String balance = "0";//钱包余额

    private LinearLayout llEmptyLayout;
    private Button tvCreateWallet;
    private Button tvRestoreWallet;

    private ImageView ivIcon;
    private TextView tvTextTitle;
    List<String> accountNameList = new ArrayList<>();
    private AccountDao accountDao;

    public EOSWalletListFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.open_planet_fragment_wallet_list, container, false);

        initView(rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWalletChanged(Account account) {
//        refreshLayout.isEnableRefresh();
//        ToastUtils.showShort("更换钱包成功");
        balance="0";
    }

    private void initView(View rootView) {
        recyclerView = rootView.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        childWalletListAdapter = new ChildWalletListAdapter(getContext(), assetList, mode);
        recyclerView.setAdapter(childWalletListAdapter);
        llEmptyLayout = (LinearLayout) rootView.findViewById(R.id.ll_empty_layout);
        tvCreateWallet = (Button) rootView.findViewById(R.id.tv_create_wallet);
        tvRestoreWallet = (Button) rootView.findViewById(R.id.tv_restore_wallet);
        refreshLayout = (SmartRefreshLayout) rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setVisibility(View.GONE);
        llEmptyLayout.setVisibility(View.VISIBLE);

        ivIcon = (ImageView) rootView.findViewById(R.id.iv_icon);
        tvTextTitle = (TextView) rootView.findViewById(R.id.tv_text_title);
        tvRestoreWallet.setOnClickListener(this);
        tvCreateWallet.setOnClickListener(this);
        initSwipeRefreshView(rootView);
    }

    /**
     * 初始化下拉刷新
     */
    private void initSwipeRefreshView(View rootView) {
        refreshLayout = rootView.findViewById(R.id.refreshLayout);
        refreshLayout.setEnableAutoLoadMore(false);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                initData();
            }
        });
    }

    private void initData() {

        ivIcon.setImageDrawable(getResources().getDrawable(R.drawable.ipasset_wallet_list_eos));
        tvTextTitle.setText("EOS");
//        if (true){
//            return;
//        }
        recyclerView.setVisibility(View.VISIBLE);
        refreshLayout.setVisibility(View.VISIBLE);
        llEmptyLayout.setVisibility(View.GONE);
        assetList.clear();
        accountDao = new AccountDao(getActivity());
        List<Account> accountList = accountDao.getAllAccount(EosNetParamUtil.getEosChainEnum());
        if (accountList.size() > 0) {

            //有btc钱包时，遍历找出当前显示的
            for (int i = 0; i < accountList.size(); i++) {
                Account account = accountList.get(i);
                if (account.isCurrentShow()) {
                    assetList.add(new AssetListBean.Builder().type(1)
                            .address(account.getAddress())
                            .name(account.getAcccountName())
                            .icon(account.getAccountAvatar())
                            .isSelected(true)
                            .build());
                    assetList.add(new AssetListBean.Builder().type(0)
                            .address(account.getAddress())
                            .name(account.getAcccountName())
                            .icon(account.getAccountAvatar())
                            .isSelected(true)
                            .build());
                }
            }
            //如果没有当前显示的，那么设第一个为当前显示的
            if (assetList.size() == 0) {
                Account account = accountList.get(0);
                account.setCurrentShow(true);
                accountDao.insertOrReplace(account);
                assetList.add(new AssetListBean.Builder().type(1)
                        .address(account.getAddress())
                        .name(account.getAcccountName())
                        .icon(account.getAccountAvatar())
                        .isSelected(true)
                        .build());
                assetList.add(new AssetListBean.Builder().type(0)
                        .address(account.getAddress())
                        .name(account.getAcccountName())
                        .icon(account.getAccountAvatar())
                        .isSelected(true)
                        .build());
            }
            childWalletListAdapter.setData(balance);
            Account account = accountDao.getAccount(assetList.get(0).getAddress());
            if (!account.isActivate()) {
                verifyIsActive(account.getPublicKey(), account.getEosActivePubKey());
            }
            childWalletListAdapter.notifyDataSetChanged();
            requestWalletBalance(assetList.get(0).getAddress());
        }else {
            //没有eos钱包，那么显示创建钱包的界面
            recyclerView.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.GONE);
            llEmptyLayout.setVisibility(View.VISIBLE);
        }
        refreshLayout.finishRefresh();
    }

    /**
     * 请求钱包余额
     *
     * @param address 钱包地址
     */
    private void requestWalletBalance(String address) {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", "eosio.token");
        map.put("accountName", address);
        map.put("chainId", String.valueOf(EosNetParamUtil.getEosChainId()));
        map.put("symbol", mode == IPAssetsConstant.CHAIN_ID_EOS ? "EOS" : "SYS");
        TCRequestUtil.postCommonRequest(TAG, "eos/get_currency_balance", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optString("result").equals("success")) {
                        JSONArray dataArray = jsonObject.optJSONArray("data");
                        balance = dataArray.optString(0);
                        if(balance.equals("")) {
                            balance = "0.00";
                        } else {
                            balance = balance.replace(mode == IPAssetsConstant.CHAIN_ID_EOS ?
                                    " EOS" : " SYS", "");
                        }
                        //将余额传给adapter，部分刷新界面，显示头部余额和第一项余额
                        childWalletListAdapter.setData(balance);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {

            }
        });
    }

    /**
     * 验证是否被激活，如果返回账号，则被激活
     * 更新数据库的账户地址
     * 再取更新后的账户，更新accountNames字段和isActive字段
     * @param pubKey　ｋｅｙ
     * @param activePubKey　ｋｅｙ
     */
    private void verifyIsActive(String pubKey, String activePubKey) {
        final Account account = accountDao.getEosAccountByActivePublicKey(activePubKey);
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("ownerPublicKey", pubKey);
        hashMap.put("activePublicKey", activePubKey);
        hashMap.put("chainId", mode + "");
        //http://tc.solarsource.cn:9692/tcserver/eos/getAccount?accountName=eosio
        TCRequestUtil.getCommonRequest(TAG, "eos/getKeyAccountsByKey", hashMap,
                new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    accountNameList.clear();
                    if (jsonObject.optString("result").equals("success")) {
                        JSONArray dataArray = jsonObject.optJSONObject("data").optJSONArray("account_names");
                        if (dataArray.length() > 0) {
                            for (int i = 0; i < dataArray.length(); i++) {
                                String accountName = dataArray.optString(i);
                                accountNameList.add(accountName);
                            }
                            accountDao.updateEosAccountName(account.getAddress(), accountNameList.get(0));
                            Account newAccount = accountDao.getAccount(accountNameList.get(0));
                            StringBuilder stringBuilder = new StringBuilder();
                            for (String account : accountNameList) {
                                stringBuilder.append(account).append("_");
                            }
                            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                            String eosAccountNames = stringBuilder.toString();
                            newAccount.setEosAccountNames(eosAccountNames);
                            newAccount.setActivate(true);
                            //激活成功，存本地
                            accountDao.insertOrReplace(newAccount);
                            childWalletListAdapter.notifyDataSetChanged();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
//        if (id == R.id.tv_create_wallet || id == R.id.tv_restore_wallet) {
//            new AlertDialog.Builder(getActivity()).setTitle("EOS")
//                    .setMessage("EOS" + "暂不支持导入， 请等待公告")
//                    .setCancelable(true)
//                    .setPositiveButton("确定", null).show();
//        }
        if (id == R.id.tv_create_wallet) {
            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_CREATE_NEW,
                    EosNetParamUtil.getEosChainId());
        } else if (id == R.id.tv_restore_wallet) {

            WalletAvatarAndNameSetupActivity.start(getActivity(), WalletTypeSelectActivity.MODE_RESTORE_OLD,
                    EosNetParamUtil.getEosChainId());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void rightTopMenuClickEvent(RightTopMenuClickEvent event) {
        StubObject stubObject = (StubObject) event.getStubObject();
        String id = stubObject.getObject("id", "").toString();
        if (id.equals("eos")) {
            //StarAssetWalletPopup.showPopup(getActivity(), event.getView(), "eos");
            StarAssetWalletPopup.showPopup(getActivity(), event.getView(), IPAssetsConstant.CHAIN_ID_EOS);

        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void optionalMarketDataEvent(OptionMarketEvent event){
        if(childWalletListAdapter!=null){
            childWalletListAdapter.setOptionMarketData(event.getKlineOptionalOrMVModels().get(2));
        }
    }
}

